package juc.producerandconsumer;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 多生产多消费
 * 使用Lock锁，效率高
 */
public class ProCon3 {
    //描述资源类
    private String name;
    private int count=1;
    private boolean flag=false;
    private ReentrantLock lock=new ReentrantLock();
    private Condition pro_condition=lock.newCondition();
    private Condition con_condition=lock.newCondition();

    public synchronized void set(String name){
        lock.lock();
      try {
          while (flag) {
              try {
                  //把该线程加入到生产者线程池
                  pro_condition.await();
              } catch (InterruptedException e) {
                  e.printStackTrace();
              }
          }
          this.name=name+"--"+count;
          count++;
          System.out.println(Thread.currentThread().getName()+"...生产者..."+this.name);
          flag=true;
          //只唤醒一个消费者
          con_condition.signal();
      }finally {
          lock.unlock();
      }
    }
    public synchronized void get(){
        lock.unlock();
        try {
            while(!flag)
                try {
                    //把该线程加入到消费者线程池
                   con_condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            System.out.println(Thread.currentThread().getName()+"...消费者..."+this.name);
            flag=false;
            //唤醒一个生产者
           pro_condition.signal();
        }finally {
            lock.unlock();
        }

    }
}

class Producer3 implements Runnable{
    private ProCon r;
    Producer3(ProCon r){
        this.r=r;
    }
    @Override
    public void run(){
        while(true)
            r.set("面包");
    }
}
class Consumer3 implements Runnable{
    private ProCon r;
    Consumer3(ProCon r){
        this.r=r;
    }
    @Override
    public void run(){
        while(true)
            r.get();
    }
}
class ProducerDemo3 {
    public static void main(String[] args) {
        ProCon r=new ProCon();
        Consumer con=new Consumer(r);
        Producer pro=new Producer(r);
        Thread t0 = new Thread(pro);
        Thread t1=new Thread(pro);
        Thread t2=new Thread(con);
        Thread t3=new Thread(con);
        t0.start();
        t1.start();
        t2.start();
        t3.start();
    }
}
